<template>
	<page-meta :page-style="popupVisible ? 'height:100%;overflow-y:hidden' : ''" />
	<view>
		<view class="search-container">
			<!-- v-model的.trim对小程序无效 -->
			<u-search :show-action="true" actionText="取消" :animation="false" shape="square"
				:placeholder="placeholder || '请输入搜索关键字'" v-model="searchVal" @change="onChange" @custom="onCustom"
				@search="onSearch">
			</u-search>
		</view>

		<template v-if="showMode === 1">
			<view class="tag-container">
				<view class="title-icon">
					<view class="text">历史记录</view>
					<u-icon name="trash" size="50rpx" @click="onDeleteHistory"></u-icon>
				</view>
				<view class="tags">
					<u-tag v-for="(item,index) in historyKeywordList" :key="index" :text="item" plain color="#969799"
						borderColor="#969799" @click="showProductList(item)">
					</u-tag>
				</view>
			</view>
			<view class="tag-container">
				<view class="title-icon">
					<view class="text">热门搜索</view>
				</view>
				<view class="tags">
					<u-tag v-for="(item,index) in hotKeywordList" :key="index" :text="item.keyword" plain
						:color="item.is_hot ? '#ee0a24' : '#969799'" :borderColor="item.is_hot ? '#ee0a24' : '#969799'"
						@click="showProductList(item.keyword)">
					</u-tag>
				</view>
			</view>
		</template>
		<template v-else>
			<!-- template不能使用v-show -->
			<view v-show="showMode === 2">
				<u-cell-group v-if="searchList.length" :customStyle="{backgroundColor:'#fff'}">
					<u-cell v-for="(item,index) in searchList" :key="index" :title="item"
						@click="showProductList(item)">
					</u-cell>
				</u-cell-group>
				<u-loadmore status="nomore" color="#969799" :nomoreText="searchList.length ? '没有更多了' : '暂无数据'" />
			</view>
			<view v-show="showMode === 3" style="background-color: #fff;padding-bottom: 50rpx;box-sizing: border-box;">
				<view class="dropdown-trigger-container">
					<view v-for="(item,index) in conditions" :key="index" class="item"
						:class="item.disabled ? 'disabled' : item.active ? 'red' : 'default'"
						@click="onClickCondition(index)">
						<view class="text">{{item.text}}</view>
						<u-icon :name="item.active ? 'arrow-up-fill' : 'arrow-down-fill'"
							:color="item.disabled ? '#bbb' : item.active ? 'red' : '#000'">
						</u-icon>
					</view>
				</view>
				<!-- 弹窗 -->
				<u-popup v-for="(item,index) in conditions" :key="index" :show="item.active" mode="top"
					:customStyle="{marginTop:popupMarginTop}" closeOnClickOverlay @close="hidePopup(index)">
					<u-cell-group>
						<template v-if="optionList[index].list.length">
							<u-cell v-for="(el,i) in optionList[index].list" :key="i" :title="el.label" clickable
								:isLink="el.value === optionList[index].currentValue" rightIcon="checkbox-mark"
								:rightIconStyle="{color:'red'}" @click="onClickCell(index,i)">
							</u-cell>
						</template>
					</u-cell-group>
				</u-popup>
				<u-loading-page :loading="true" v-if="!hasFetchedData"></u-loading-page>
				<view v-if="hasFetchedData && goodsList.length">
					<view v-for="item in goodsList">
						<goodsList :list="item"></goodsList>
					</view>
				</view>
				<u-loadmore v-if="hasFetchedData && currentPage === totalPages" status="nomore" color="#969799"
					nomoreText="没有更多了" />
				<u-empty v-if="hasFetchedData && !goodsList.length" mode="search"
					icon="http://cdn.uviewui.com/uview/empty/search.png">
				</u-empty>
			</view>
		</template>


	</view>
</template>

<script>
	import {
		SIZE
	} from "../../config/config.js"
	import {
		searchIndexApi, //搜索窗口数据
		ClearHistory, //清除历史记录
		searchHelper, //实时搜索功能
		goodsListApi //搜索框窗口数据
	} from "../request/api.js"
	import request from "@/pages/request/request.js"
	import uniList from "@/node_modules/uview-ui/components/u-list/u-list.vue"
	let timer = null

	export default {
		components: {
			uniList
		},
		data() {
			return {
				searchVal: '',
				placeholder: '',
				historyKeywordList: [],
				hotKeywordList: [],
				showMode: 1,
				stayInMode3: false,
				searchList: [],
				goodsList: [],
				currentPage: 1,
				totalPages: 0,
				conditions: [{
					disabled: true,
					text: '综合',
					active: false
				}, {
					disabled: false,
					text: '价格',
					active: false
				}, {
					disabled: false,
					text: '分类',
					active: false
				}],
				popupVisible1: false,
				optionList: [{
						list: [],
						currentValue: ''
					},
					{
						list: [{
								label: '由高到低',
								value: 'desc',
							},
							{
								label: '由低到高',
								value: 'asc',
							},
						],
						currentValue: ''
					},
					{
						list: [],
						currentValue: 0
					}
				],
				sort: 'id',
				hasFetchedData: false,
				searchContainerHeight: 0,
				dropdownTriggerContainerHeight: 0,
			};
		},
		computed: {
			popupVisible() {
				return this.conditions.some(el => {
					return el.active
				})
			},
			popupMarginTop() {
				return this.searchContainerHeight + this.dropdownTriggerContainerHeight + 'px'
			}
		},
		onLoad() {
			this.getSearchIndexData()
		},
		onReady() {
			// 获取元素
			const query = uni.createSelectorQuery().in(this)
			query.select('.search-container').boundingClientRect(data => {
				console.log(data)
				this.searchContainerHeight = data.height
			}).exec()
		},
		onReachBottom() {
			console.log('触底')
			if (this.currentPage < this.totalPages) {
				this.currentPage += 1
				this.showProductList(this.searchVal)
			}
		},
		methods: {
			// 获取搜索窗口数据
			getSearchIndexData() {
				request({
					url: searchIndexApi,
					successCb: res => {
						console.log(res)
						const {
							defaultKeyword,
							historyKeywordList,
							hotKeywordList
						} = res
						this.placeholder = defaultKeyword.keyword
						this.historyKeywordList = historyKeywordList
						this.hotKeywordList = hotKeywordList
					}
				})
			},
			onChange(val) {
				if (this.stayInMode3) {
					this.stayInMode3 = false
					return
				}
				if (timer) {
					clearTimeout(timer)
				}
				timer = setTimeout(() => {
					console.log(val)
					this.showMode = 2
					this.goodsList = []
					this.totalPages = 0
					this.currentPage = 1
					this.optionList[1].currentValue = ''
					this.optionList[2].list = []
					this.optionList[2].currentValue = 0
					this.hasFetchedData = false
					request({
						url: searchHelper,
						data: {
							keyword: val.trim()
						},
						successCb: res => {
							console.log(res)
							this.searchList = res
						}
					})
				}, 300)
			},
			onCustom() {
				this.searchVal = ''
				uni.navigateBack()
			},
			onSearch(val) {
				console.log(val)
				this.showProductList(val)
			},
			// 删除历史记录
			onDeleteHistory() {
				request({
					url: ClearHistory,
					successCb: res => {
						this.getSearchIndexData()
					}
				})
			},
			// 展示产品列表
			showProductList(keyword) {
				this.stayInMode3 = true
				this.searchVal = keyword
				this.showMode = 3
				// 这里需要在this.$nextTick中才能获取到信息
				this.$nextTick(() => {
					const query = uni.createSelectorQuery().in(this)
					query.select('.dropdown-trigger-container').boundingClientRect(data => {
						console.log(data)
						this.dropdownTriggerContainerHeight = data.height
					}).exec()
				})

				console.log(keyword)

				request({
					url: goodsListApi,
					data: {
						keyword,
						page: this.currentPage,
						size: SIZE,
						sort: this.sort,
						categoryId: this.optionList[2].currentValue,
						order: this.optionList[1].currentValue,
					},
					successCb: res => {
						console.log(res)
						let {
							goodsList,
							totalPages,
							filterCategory
						} = res

						let result = []
						goodsList.forEach((el, index) => {
							if (index % 2 === 0) {
								result.push([])
							}
							if (result[result.length - 1].length < 2) {
								result[result.length - 1].push(el)
							}
						})
						this.goodsList = [...this.goodsList, ...result]
						this.totalPages = totalPages

						// 下拉菜单
						this.optionList[2].list = filterCategory.map(el => {
							return {
								label: el.name,
								value: el.id
							}
						})
						let checkedItem = filterCategory.find(el => {
							return el.checked
						})
						if (checkedItem) {
							this.optionList[2].currentValue = checkedItem.id
						}


						this.stayInMode3 = false
						this.hasFetchedData = true
					},
					failCb: () => {
						this.stayInMode3 = false
						this.hasFetchedData = true
					}
				})


			},


			onClickCondition(index) {
				if (!this.conditions[index].disabled) {
					if (this.conditions[index].active) {
						this.conditions[index].active = false
					} else {
						const activeItem = this.conditions.find(el => {
							return el.active
						})
						if (activeItem) {
							activeItem.active = false
						}
						this.conditions[index].active = true
					}
				}
			},
			hidePopup(index) {
				this.conditions[index].active = false
			},
			onClickCell(index1, index2) {
				if (this.optionList[index1].list.length) {
					const before = this.optionList[index1].currentValue
					this.optionList[index1].currentValue = this.optionList[index1].list[index2].value
					if (before !== this.optionList[index1].currentValue) {
						console.log(`第${index1}个菜单的第${index2}个弹窗标题被点击了，它的值为${this.optionList[index1].currentValue}`)
						if (index1 === 1) {
							this.sort = 'price'
						} else if (index1 === 2) {
							this.sort = 'id'
						}
						this.goodsList = []
						this.currentPage = 1
						this.totalPages = 0
						this.hasFetchedData = false
						this.showProductList(this.searchVal)
					}
					this.hidePopup(index1)
				}
			},
		}
	}
</script>

<style lang="scss" scoped>
	page {
		background-color: #efefef;

		.search-container {
			padding: 20rpx 24rpx;
			background-color: #fff;
			position: relative;
			z-index: 11000;
		}

		.tag-container {
			margin-bottom: 40rpx;
			padding: 20rpx;
			background-color: #fff;
			additive-symbols: 40rpx;

			.title-icon {
				display: flex;
				align-items: center;
				justify-content: space-between;
				font-size: 36rpx;
				margin-bottom: 20rpx;
			}

			.tags {
				display: flex;
				flex-wrap: wrap;
			}

			/deep/ .u-tag-wrapper {
				display: inline-block;
				margin-right: 20rpx;
				margin-bottom: 20rpx;
			}

			/deep/ .u-tag {
				display: inline-block;
			}
		}

		/deep/ .uni-list-item__container {
			padding-left: 20rpx;
			padding-right: 20rpx;
		}

		/deep/ .uni-list-item__header,
		/deep/ .uni-list--border {
			display: none;
		}

		.row {
			display: flex;
			justify-content: space-between;

			.product-item {
				width: 49%;
				position: relative;
				padding-bottom: 20rpx;
				margin-bottom: 20rpx;

				.img {
					width: 347.9rpx;
					height: 347.9rpx;
				}

				.text,
				.price {
					font-size: 28rpx;
					text-align: center;
				}

				.text {
					margin-bottom: 10rpx;
					width: 100%;
					white-space: nowrap;
					text-overflow: ellipsis;
					overflow: hidden;
				}

				.price {
					color: darkred;
				}
			}
		}

		.dropdown-trigger-container {
			display: flex;
			height: 50px;
			background-color: #fff;
			border-bottom: 1px solid #eee;
			position: relative;
			z-index: 11000;

			.item {
				flex: 1;
				height: 100%;
				display: flex;
				justify-content: center;
				align-items: center;

				&.default {
					color: #000;
				}

				&.red {
					color: red;
				}

				&.disabled {
					color: #bbb;
				}
			}
		}
	}

	/deep/ .u-safe-area-inset-bottom {
		padding-bottom: 0;
	}
</style>
